package com.custom.topic;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 *
 */
@Configuration
@EnableRabbit
@ComponentScan("com.custom.topic")
public class TopicMqConfiguration {

    public static final String EXCHANGE_NAME = "topicB";
    @Bean
    public CachingConnectionFactory connectionFactory() {
        return new CachingConnectionFactory("localhost");
    }

    @Bean
    public RabbitAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }

    @Bean
    public Queue myQueueA() {
        //调用nonDurable时队列的名字自动生成
        return QueueBuilder.nonDurable("q1").autoDelete().build();
    }

    @Bean
    public Queue myQueueB() {
        //调用nonDurable时队列的名字自动生成
        return QueueBuilder.nonDurable("q2").autoDelete().build();
    }

    @Bean
    public TopicExchange topicExchange(){
        TopicExchange topicExchange = new TopicExchange(EXCHANGE_NAME);
        return topicExchange;
    }

    @Bean
    public Binding bindingA(){
        return BindingBuilder.bind(myQueueA()).to(topicExchange()).with("*.orange.*");
    }

    @Bean
    public Binding bindingB(){
        return BindingBuilder.bind(myQueueB()).to(topicExchange()).with("*.*.rabbit");
    }
    @Bean
    public Binding bindingC(){
        return BindingBuilder.bind(myQueueB()).to(topicExchange()).with("lazy.#");
    }

    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        //设置发送消息的消息转换器
        template.setMessageConverter(messageConverter());
        return template;
    }


    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        //设置接收消息的消息转换器
        factory.setMessageConverter(messageConverter());

        return factory;
    }
}
